package com.platform.modules.app.controller;

import com.platform.modules.mall.service.MallOrderService;
import com.platform.modules.mall.service.MallPhoneTopUpLogService;
import com.platform.modules.phone.PhoneTopUpContants;
import com.platform.modules.phone.config.PhoneCommonConfig;
import com.platform.modules.phone.entity.dto.PhoneTopUpCallBackDto;
import com.platform.modules.phone.service.PhoneTopUpService;
import com.platform.modules.phone.utils.PhoneTopUpUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.net.URLDecoder;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/app/phoneTopUp/")
public class AppPhoneTopUpController {

    @Resource
    MallPhoneTopUpLogService phoneTopUpLogService;
    @Resource
    MallOrderService orderService;
    @Resource(name = "phoneCommonConfig")
    private PhoneCommonConfig config;
    @Resource
    private PhoneTopUpService phoneTopUpService;

    /**
     * 手机充值完成后 回调
     *
     * @return
     */
    @PostMapping(value = "/callBack")
    public String topupCallback(HttpServletRequest request) throws Exception {
        try {
            //参数解析
            Map<String, String> paramsMap = conventParams(request);
            String orderInfo = paramsMap.get("Orderinfo");
            String sign = paramsMap.get("Sign");
            log.info("--------开始处理回调手机充值成功回调-------");
            log.info("参数Orderinfo:{}", orderInfo);
            log.info("参数Sign:{}", sign);

            // 签名验证
            String onwersign = PhoneTopUpUtils.sign(orderInfo, config.getKey(),
                    Charset.forName(PhoneTopUpContants.RES_CHARSET));
            if (!onwersign.equals(sign)) {
                log.info("--------手机充值回调处理:签名验证失败-------");
                log.info("自己计算出来的签名Sign:{}", onwersign);
                return PhoneTopUpContants.CALL_BACK_HANDLE_ERROR;
            }
            log.info("--------手机充值回调处理:签名验证成功------");

            //处理业务
            PhoneTopUpCallBackDto dto = PhoneTopUpUtils.buildObjByResponseInfo(orderInfo, PhoneTopUpCallBackDto.class);
            phoneTopUpService.topupCallBack(dto);
            log.info("--------手机充值回调处理:成功-------");
            return PhoneTopUpContants.CALL_BACK_HANDLE_SUCCESS;
        } catch (Exception e) {
            log.error("--------手机充值回调处理--异常:{}-------", e);
            log.error("--------手机充值回调处理--异常位置:{}-------", e.getStackTrace());
            return PhoneTopUpContants.CALL_BACK_HANDLE_ERROR;
        }
    }


    /**
     * 充值成功回调的参数转换
     * 从request的inputStream 读取参数后 并解析为Map
     *
     * @param request 请求
     * @return
     * @throws IOException
     */
    private Map<String, String> conventParams(HttpServletRequest request) throws IOException {
        Map<String, String> paramsMap = new HashMap<>();

        // 从 inputstream中 读取参数
        String params = IOUtils.toString(request.getInputStream(), PhoneTopUpContants.RES_CHARSET);

        // 分割参数列表 并进行解析
        String[] paramsSplit = params.split("&");
        for (String param : paramsSplit) {
            String[] paramSplit = param.split("=");
            String key = paramSplit[0];

            // 值读取的时候 进行URLencoding 解码
            String value = URLDecoder.decode(paramSplit[1], PhoneTopUpContants.RES_CHARSET);
            paramsMap.put(key, value);
        }
        return paramsMap;
    }


}
